<template>
  <view>
    <u-upload
      :fileList="img"
      @afterRead="afterRead"
      @delete="deletePic"
      name="1"
      multiple
      :maxCount="maxCount"
    >
    </u-upload>
  </view>
</template>

<script>
import { requestPost, requestGet } from "@/util/request";
import { pathToBase64, base64ToPath } from "image-tools";
export default {
  props: {
    imgList: {
      type: Array,
      default: () => [],
    },
    maxCount: {
      type: Number,
      default: 3,
    },
  },
  data() {
    return {
      img: [],
    };
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this.img.splice(event.index, 1);
      this.submit();
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      // console.log("event.file", event.file);
      let fileListLen = this.img.length;
      lists.map((item) => {
        this.img.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        // 图片转化为base64格式
        const base64 = await this.convertToBase64(lists[i].url);
        // const result = await this.uploadFilePromise(lists[i].url, event.file);
        let item = this.img[fileListLen];
        this.img.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: base64,
          })
        );
        fileListLen++;
      }
      this.submit();
    },
    async convertToBase64(url) {
      let base64Data = null;
      // 图片转化为base64格式
      await pathToBase64(url).then((data) => {
        // console.log("convertToBase64", data);
        base64Data = data;
      });
      return base64Data;
    },
    uploadFilePromise(url, file) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: "http://39.104.66.177:73/prod-api/fileSystem/fileUpload/uploadFile",
          filePath: file[0].url,
          name: "file",
          success: function (res) {
            let savedFilePath = res.data?.id;
            resolve(savedFilePath);
          },
        });
      });
    },
    submit() {
      this.$emit("submit", this.img);
    },
  },
  created() {
    this.img = this.imgList;
  },
};
</script>

<style></style>
